<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header
        :content="id ? '编辑月卡' : '增加月卡'"
        @back="$router.back()"
      />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <!-- 车辆信息 -->
          <el-form
            ref="carInfoForm"
            label-width="100px"
            :model="carInfoForm"
            :rules="carInfoRules"
          >
            <el-form-item label="车主姓名" prop="personName">
              <el-input
                v-model="carInfoForm.personName"
                placeholder="请输入车主姓名"
              />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input
                v-model="carInfoForm.phoneNumber"
                placeholder="请输入联系方式"
              />
            </el-form-item>
            <el-form-item label="车牌号码" prop="carNumber">
              <el-input
                v-model="carInfoForm.carNumber"
                placeholder="请输入车牌号码"
              />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input
                v-model="carInfoForm.carBrand"
                placeholder="请输入车辆品牌"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <!-- 缴费信息 -->
          <el-form
            ref="feeForm"
            label-width="100px"
            :model="feeForm"
            :rules="feeRuls"
          >
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker
                v-model="feeForm.payTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input
                v-model="feeForm.paymentAmount"
                placeholder="请输入支付金额"
              />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option
                  v-for="item in payMethodList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="hReset">重置</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addMonthCardAPI, getMonthCardDetailAPI, updateMonthCardAPI } from '@/api/card'
export default {
  name: 'AddMonthCard',
  data() {
    // 车牌自定义校验方法
    // value 输入框的内容
    // callback 函数 如果验证失败 return callback(new Error('失败的原因'))
    // callback 函数 如果验证成功 callback()
    const checkCarNumber = function(rule, value, callback) {
      // 定义正则
      const reg =
        /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/
      // 判断 输入的内容是否符合正则
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('请输入合法的车牌号码'))
      }
    }
    return {
      pickerOptions: {
        disabledDate(time) {
          // console.log(time)
          // 禁止选择今天之前的日期
          // console.log()
          return time.getTime() < Date.now() - 86400 * 1000
        }
      },
      // 车辆信息
      carInfoForm: {
        personName: '', // 车主姓名
        phoneNumber: '', // 联系方式
        carNumber: '', // 车牌号码
        carBrand: '' // 车辆品牌
      },
      carInfoRules: {
        personName: [
          {
            required: true,
            message: '请输入车主姓名',
            trigger: 'blur'
          }
        ],
        phoneNumber: [
          {
            required: true,
            message: '请输入联系方式',
            trigger: 'blur'
          },
          {
            pattern:
              /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            message: '请输入合法的手机号码',
            trigger: 'blur'
          }
        ],
        carNumber: [
          {
            required: true,
            message: '请输入车辆号码',
            trigger: 'blur'
          },
          { validator: checkCarNumber, trigger: 'blur' }
        ],
        carBrand: [
          {
            required: true,
            message: '请输入车辆品牌',
            trigger: 'blur'
          }
        ]
      },
      feeForm: {
        payTime: '', // 支付时间
        paymentAmount: null, // 支付金额
        paymentMethod: '' // 支付方式
      },
      feeRuls: {
        payTime: [
          {
            required: true,
            message: '请选择支付时间'
          }
        ],
        paymentAmount: [
          {
            required: true,
            message: '请输入支付金额',
            trigger: 'blur'
          }
        ],
        paymentMethod: [
          {
            required: true,
            message: '请选择支付方式',
            trigger: 'change'
          }
        ]
      },
      // 支付方式列表
      payMethodList: [
        {
          id: 'Alipay',
          name: '支付宝'
        },
        {
          id: 'WeChat',
          name: '微信'
        },
        {
          id: 'Cash',
          name: '线下'
        }
      ]
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  created() {
    // 如果 有 id 才获取当前的月卡详情数据
    if (this.id) {
      this.getMonthCardDetail()
    }
  },
  methods: {
    // 点击确定按钮
    onSubmit() {
      // 对两个表单进行兜底校验
      // Promise.all(数组) 数组里面 放的是 Promise对象
      const promises = [
        this.$refs.carInfoForm.validate(),
        this.$refs.feeForm.validate()
      ]
      Promise.all(promises)
        .then(async() => {
          try {
            const obj = {
              ...this.carInfoForm,
              ...this.feeForm,
              cardStartDate: this.feeForm.payTime[0],
              cardEndDate: this.feeForm.payTime[1]
            }
            delete obj.payTime
            if (this.id) {
              // 编辑月卡
              await updateMonthCardAPI(obj)
              // 提示消息
              this.$message.success('月卡编辑成功')
            } else {
              // 添加月卡
              // 调用 addMonthCard 发送请求
              await addMonthCardAPI(obj)
              // 提示消息
              this.$message.success('月卡添加成功')
            }
            // 回退
            this.$router.back()
          } catch (error) {
            if (error.response) {
              this.$message.error(error.response.data.msg)
            }
          }
        })
        .catch(() => {
          console.log('有表单验证不通过')
        })
    },
    hReset() {
      this.$refs.carInfoForm.resetFields()
      this.$refs.feeForm.resetFields()
    },
    // 获取月卡详情
    async getMonthCardDetail() {
      try {
        // 调用 getMonthCardDetailAPI 函数
        const res = await getMonthCardDetailAPI(this.id)
        // 对象解构
        const { personName, phoneNumber, carNumber, carBrand, carInfoId } = res.data
        // 将数据写入到 this.carInfoForm 对象
        this.carInfoForm = {
          personName, phoneNumber, carNumber, carBrand, carInfoId
        }
        // 对象解构
        const { cardStartDate, cardEndDate, paymentAmount, paymentMethod, rechargeId } = res.data
        this.feeForm = {
          payTime: [cardStartDate, cardEndDate],
          paymentAmount,
          paymentMethod,
          rechargeId
        }
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
